package cn.xu.bookstore.book.dao;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.itcast.commons.CommonUtils;
import cn.itcast.jdbc.TxQueryRunner;
import cn.xu.bookstore.book.domain.Book;
import cn.xu.bookstore.category.domain.Category;

public class BookDao {
	private QueryRunner qr = new TxQueryRunner();
	
	
	public List<Book> findAll(){
		String sql ="select * from book where del=false";
		try {
			return qr.query(sql, new BeanListHandler<Book>(Book.class));
		} catch (SQLException e) {
			throw new RuntimeException();
		}
	}
	
	public List<Book> findByCategory(String cid){
		String sql ="select * from book where cid =?";
		try {
			return qr.query(sql, new BeanListHandler<Book>(Book.class),cid);
		} catch (SQLException e) {
			throw new RuntimeException();
		}
	}

	public Book findByBid(String bid) {
		String sql = "select * from book where bid = ?";
		Book book = null;
		try {
			 Map<String,Object> map = qr.query(sql, new MapHandler(),bid);
			book = CommonUtils.toBean(map, Book.class);
			/*
			 * 为了让book中出现所属分类 cid
			 */
			Category category = CommonUtils.toBean(map, Category.class);
			book.setCategory(category);
			 
			
		} catch (SQLException e) {
			throw new RuntimeException();
		}
		return  book;
	}

	public int getCountByCid(String cid) {
		String sql ="select count(*) from book where cid=?";
		int count = 0;
		try {
			Number _count = (Number)qr.query(sql, new ScalarHandler(),cid);
			count = _count.intValue();
		} catch (SQLException e) {
			throw new RuntimeException();
		}
		return count;
	}

	public void updateBook(Book book) {
System.out.println(book.getPrice());
		String sql = "update book set bname=? , price=? , author=? , cid =? where bid=?";
		Object[] params = {book.getBname(),book.getPrice(),book.getAuthor(),book.getCategory().getCid(),
				book.getBid()};
		 try {
			qr.update(sql,params);
		} catch (SQLException e) {
			throw new RuntimeException();
		}
		
		
	}

	public void delete(String bid) {
		
		String sql="update book set del = true where bid = ?";
		try {
			qr.update(sql,bid);
		} catch (SQLException e) {
			throw new RuntimeException();
		}
		
	}

	public void add(Book book) {
		
		String sql = "insert into book values(?,?,?,?,?,?,?)";
		Object[] params = {book.getBid(),book.getBname(),book.getPrice(),book.getAuthor(),book.getImage(),
				book.getCategory().getCid(),book.getDel()};
		try {
			qr.update(sql,params);
		} catch (SQLException e) {
			throw new RuntimeException();
		}
	}
	
	

}
